//
//  OAuthViewController.swift
//  LEOweibo
//
//  Created by zz on 16/2/26.
//  Copyright © 2016年 zz. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    
    private lazy var webView: UIWebView = UIWebView()
    override func loadView() {
        view = webView
        
        setUpUI()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oAuthURL))
        webView.delegate = self
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    //设置授权控制器的界面
    func setUpUI() {
        title = "登录新浪weibo"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "didClickAutoWriteButton")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "didClickCancelButton")
    }
    
    //点击了取消按钮
    func didClickCancelButton() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    //点击了自动填充按钮
    func didClickAutoWriteButton() {
        let js = "document.getElementById('userId').value='18221147372';" +
        "document.getElementById('passwd').value='zzz123';"

        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
}

extension OAuthViewController : UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
    
        if let urlString = request.URL?.absoluteString where !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri){
        return true
            
    }

        guard let query = request.URL?.query where query.hasPrefix("code=") else {
            
            print("取消授权")
            return false
        }
        let code = query.substringFromIndex("code=".endIndex)
        
        NetworkTools.sharedTools.loadAccessToken(code) { (userDict) -> () in
            
            guard let userDict = userDict else{
                print("数据加载失败")
                return
            }
            
//            UserAccount.sharedUserAccount.upDateUserCount(userDict)

            UserAccount.sharedUserAccount.updateDate(userDict)
            
            NSNotificationCenter.defaultCenter().postNotificationName(LeoLoginSuccessedNotification, object: nil)
            
            self.didClickCancelButton()
            
        }
        
        
        
    
    
    
    
    return true
}
}





